package com.hjm.common.api.cq;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author puyiliang
 * @date create in 2021/1/13 10:04
 */
@SuppressWarnings("All")
public class HttpRequestUtil {

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param JSONString。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPostJson(String httpUrl, String params) {
        //生产HttpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        CloseableHttpClient client = HttpClients.createDefault();
        StringEntity entity = new StringEntity(params, "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        try {
            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity responseEntity = response.getEntity();
                return EntityUtils.toString(responseEntity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(client!= null){
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
}
